# -*- coding: utf-8 -*-
"""
****************************
@Time    : 2021/4/25 15:45
@Author  : Candy
@File    : user.py
****************************
"""
import datetime

from flask import Blueprint, request, jsonify
from flask_sqlalchemy import SQLAlchemy

from get_area_by_ip import get_area
from middlewares.auth import login_and_auth_middleware
from models.response import MyResponse
from models.users import User
from serializers.user import check_name_pwd_tel, check_pwd_tel
from utils.auth import MiniJWT
from utils.normal import serializer_pwd
from flask_cors import *

user = Blueprint('user', __name__)


@user.route('/', methods=["GET"])
def get_user():
    return b'get user'


@user.route('/register/', methods=['POST'])
@cross_origin()
def register():
    res = MyResponse()
    db = SQLAlchemy()
    name = request.form.get('name', '')
    password = request.form.get('pwd', '')
    tel = request.form.get('tel', '')
    tel_coding = request.form.get('tel_code', '')
    if not check_name_pwd_tel(name=name, pwd=password, tel=tel) or tel_coding != '888888':
        res.status = 'error'
        res.code = 201
        res.results['message'] = "注册失败1"
    else:
        new_user = User()
        new_user.name = str(name)
        new_user.pwd = serializer_pwd(password)
        new_user.tel = tel
        try:
            db.session.add(new_user)
            db.session.commit()
            res.status = 'success'
            res.results['message'] = "注册成功"
        except Exception as e:
            db.session.rollback()
            res.status = 'error'
            res.code = 201
            res.results['message'] = "注册失败(账户已存在)"
    return jsonify(res.data())


@user.route('/login/', methods=['POST'])
@cross_origin()
def login():
    auth = MiniJWT()
    res = MyResponse()
    db = SQLAlchemy()
    pwd = request.form.get('pwd', '')
    tel = request.form.get('tel', '')
    ip = request.remote_addr
    ua = request.user_agent
    if check_pwd_tel(pwd=pwd, tel=tel):
        login_user = db.session.query(User).filter(User.tel == tel).filter(User.pwd == serializer_pwd(pwd)).filter(User.is_del == 0).first()
        if login_user:
            token = auth.build(login_user.id, ip, ua.string)
            try:
                login_user.last_sign_area = get_area(ip)
                login_user.last_sign_time = datetime.datetime.now()
                db.session.add(login_user)
                db.session.commit()
            except Exception:
                db.session.rollback()
            res.status = 'success'
            res.results['message'] = '登录成功'
            res.results['token'] = token
            res.results['username'] = login_user.name
            res.results['user_image_path'] = login_user.head_avator
            res.results['agree_count'] = login_user.agree_count
            res.results['view_count'] = login_user.view_count
            res.results['blog_count'] = login_user.blog_count
            res.results['last_sign_time'] = str(login_user.last_sign_time)
            res.results['last_sign_area'] = login_user.last_sign_area
            res.results['slogan'] = login_user.slogan
        else:
            res.status = 'error'
            res.code = '201'
            res.results['message'] = '密码错误'
    else:
        res.status = 'error'
        res.code = '201'
        res.results['message'] = '非法请求'
    return jsonify(res.data())


@user.route('/tel_code/', methods=['GET'])
def tel_code():
    res = MyResponse()
    res.results['message'] = '短信服务暂停！ 统一验证码为888888'
    return jsonify(res.data())


@user.route('/auth', methods=['POST'])
@cross_origin()
@login_and_auth_middleware
def mini_auth(aid):
    res = MyResponse()
    db = SQLAlchemy()
    login_user = db.session.query(User.level, User.id).filter(User.id == aid).filter(User.is_del == 0).first()
    if not login_user:
        res.code = 201
        res.status = 'error'
        res.results['message'] = '无效用户'
    else:
        res.code = 200
        res.status = 'success'
        res.results['message'] = ''
    return jsonify(res.data())
